<template>
  <view class="container">
    <view class="assessment-form">
      <!-- 患者信息显示 -->
      <view class="patient-info-card">
        <view class="card-header">
          <text class="card-title">📋 患者档案</text>
          <text class="doctor-tag">{{ doctorName }}</text>
        </view>
        
        <view class="info-grid">
          <view class="info-item">
            <text class="info-label">姓名</text>
            <text class="info-value">{{ patientInfo.real_name || '未知' }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">性别</text>
            <text class="info-value">{{ patientInfo.gender === 1 ? '男' : patientInfo.gender === 0 ? '女' : '未知' }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">年龄</text>
            <text class="info-value">{{ patientInfo.age || '-' }}岁</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">手机号</text>
            <text class="info-value">{{ patientInfo.phone || '未提供' }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">绑定医生</text>
            <text class="info-value">{{ doctorFullName || '未知' }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">医生电话</text>
            <text class="info-value">{{ doctorPhone || '未提供' }}</text>
          </view>
        </view>
      </view>

      <!-- 评估日期选择 -->
      <view class="form-group">
        <text class="form-label">评估日期</text>
        <picker mode="date" :value="assessmentDate" @change="onDateChange">
          <view class="picker-input">
            <text class="picker-text">{{ assessmentDate || '请选择日期' }}</text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>

      <!-- 量表选择 -->
      <view class="form-group">
        <text class="form-label">选择量表</text>
        <view class="scale-options">
          <view class="scale-option" :class="{ active: selectedScales.includes('hamd') }" @tap="toggleScale('hamd')">
            <text class="scale-name">抑郁量表 (HAMD)</text>
            <text class="scale-desc">汉密尔顿抑郁量表</text>
          </view>
          <view class="scale-option" :class="{ active: selectedScales.includes('hama') }" @tap="toggleScale('hama')">
            <text class="scale-name">焦虑量表 (HAMA)</text>
            <text class="scale-desc">汉密尔顿焦虑量表</text>
          </view>
          <view class="scale-option" :class="{ active: selectedScales.includes('ymrs') }" @tap="toggleScale('ymrs')">
            <text class="scale-name">躁狂量表 (YMRS)</text>
            <text class="scale-desc">杨氏躁狂评定量表</text>
          </view>
        </view>
      </view>

      <!-- 评估备注 -->
      <view class="form-group">
        <text class="form-label">评估备注</text>
        <textarea 
          class="textarea-input" 
          v-model="assessmentNotes" 
          placeholder="请输入评估备注（可选）"
          maxlength="500"
        ></textarea>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" @tap="createAssessment" :disabled="!canSubmit">
        创建评估
      </button>
    </view>
  </view>
</template>

<script>
import { createAssessment, getUserInfo } from '../../../utils/api/doctor.js';
import { getLoginStatus, saveUserInfo } from '../../../utils/auth.js';
import { getUserInfo as getCurrentUserInfo } from '../../../utils/api/auth.js';

export default {
  data() {
    return {
      patientUserId: '',
      patientInfo: {},
      doctorName: '',
      doctorFullName: '',
      doctorPhone: '',
      assessmentDate: '',
      selectedScales: [],
      assessmentNotes: '',
      loading: false
    }
  },
  computed: {
    canSubmit() {
      return this.assessmentDate && this.selectedScales.length > 0;
    }
  },
  onLoad(options) {
    if (options.patientUserId) {
      this.patientUserId = options.patientUserId;
      this.loadPatientInfo();
    }
    // 设置默认日期为今天
    this.assessmentDate = this.formatDate(new Date());
    // 加载医生信息
    this.loadDoctorInfo();
  },
  methods: {
    // 加载患者信息
    async loadPatientInfo() {
      try {
        console.log('[创建评估] 加载患者信息, patientUserId:', this.patientUserId);
        const response = await getUserInfo(this.patientUserId);
        console.log('[创建评估] 患者信息响应:', response);
        
        if (response && response.code === 200 && response.data) {
          this.patientInfo = {
            real_name: response.data.real_name,
            gender: response.data.gender,
            age: response.data.age,
            phone: response.data.phone,
            id_card: response.data.id_card
          };
          console.log('[创建评估] 患者信息加载成功:', this.patientInfo);
        }
      } catch (error) {
        console.error('[创建评估] 加载患者信息失败:', error);
        uni.showToast({
          title: '加载患者信息失败',
          icon: 'none'
        });
      }
    },
    
    // 加载医生信息
    async loadDoctorInfo() {
      try {
        // 先从本地获取
        const loginStatus = getLoginStatus();
        let userInfo = loginStatus.userInfo || {};
        
        // 从API获取最新医生信息
        try {
          const response = await getCurrentUserInfo();
          console.log('[创建评估] 从API获取医生信息:', response);
          
          if (response && response.code === 200 && response.data) {
            userInfo = response.data;
            // 更新本地存储
            saveUserInfo(userInfo);
            console.log('[创建评估] 医生信息已更新:', userInfo);
          }
        } catch (apiError) {
          console.warn('[创建评估] 从API获取医生信息失败，使用本地缓存:', apiError);
        }
        
        // 获取医生完整姓名
        const fullName = userInfo.real_name || userInfo.wechat_name || '';
        this.doctorFullName = fullName || '未知';
        
        // 设置简称（姓氏+医生）用于右上角标签
        if (fullName && fullName.length > 0) {
          this.doctorName = fullName.charAt(0) + '医生';
        } else {
          this.doctorName = '医生';
        }
        
        // 获取医生电话
        this.doctorPhone = userInfo.phone || '未提供';
        
        console.log('[创建评估] 医生信息:', {
          fullName: fullName,
          doctorName: this.doctorName,
          doctorFullName: this.doctorFullName,
          doctorPhone: this.doctorPhone
        });
      } catch (error) {
        console.error('[创建评估] 加载医生信息失败:', error);
        this.doctorName = '医生';
        this.doctorFullName = '未知';
        this.doctorPhone = '未提供';
      }
    },
    
    // 日期选择
    onDateChange(e) {
      this.assessmentDate = e.detail.value;
    },
    
    // 切换量表选择
    toggleScale(scaleType) {
      const index = this.selectedScales.indexOf(scaleType);
      if (index > -1) {
        this.selectedScales.splice(index, 1);
      } else {
        this.selectedScales.push(scaleType);
      }
    },
    
    // 创建评估
    async createAssessment() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善必填信息',
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      
      try {
        // 计算总分（这里先用默认值，实际应该根据量表内容计算）
        const hamdTotal = this.selectedScales.includes('hamd') ? 0 : 0;
        const hamaTotal = this.selectedScales.includes('hama') ? 0 : 0;
        const ymrsTotal = this.selectedScales.includes('ymrs') ? 0 : 0;
        
        const response = await createAssessment(
          this.patientUserId,
          this.assessmentDate,
          hamdTotal,
          hamaTotal,
          ymrsTotal
        );
        
        if (response.code === 200) {
          uni.showToast({
            title: '评估创建成功',
            icon: 'success'
          });
          
          // 跳转到量表填写页面，只跳转到第一个选中的量表
          setTimeout(() => {
            const firstScale = this.selectedScales[0];
            let url = '';
            
            if (firstScale === 'hamd') {
              url = `/pages/yiYuLiangBiaoStarter/yiYuLiangBiaoStarter?assessmentId=${response.data.assessment_id}&patientId=${this.patientUserId}`;
            } else if (firstScale === 'hama') {
              url = `/pages/jiaoLvLiangBiao/jiaoLvLiangBiao?assessmentId=${response.data.assessment_id}&patientId=${this.patientUserId}`;
            } else if (firstScale === 'ymrs') {
              url = `/pages/kuangZaoLiangBiao/kuangZaoLiangBiao?assessmentId=${response.data.assessment_id}&patientId=${this.patientUserId}`;
            }
            
            if (url) {
              uni.navigateTo({ url });
            }
          }, 1500);
        } else {
          uni.showToast({
            title: response.msg || '创建失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('创建评估失败:', error);
        uni.showToast({
          title: '创建评估失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style scoped>
.container {
  padding-bottom: 80rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.assessment-form {
  padding: 30rpx 30rpx 30rpx;
}

.patient-info-card {
  background: linear-gradient(135deg, #fff 0%, #f8fcff 100%);
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(90, 184, 157, 0.15);
  border: 2rpx solid #5AB89D;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #e8f5f1;
}

.card-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.doctor-tag {
  background: linear-gradient(135deg, #5AB89D 0%, #4aa58b 100%);
  color: #fff;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 500;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  padding: 12rpx;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 10rpx;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-label {
  font-size: 22rpx;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 26rpx;
  color: #333;
  font-weight: 600;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 26rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
  font-weight: 600;
}

.picker-input {
  background: #fff;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.picker-arrow {
  font-size: 24rpx;
  color: #999;
}

.scale-options {
  display: flex;
  flex-direction: column;
  gap: 14rpx;
}

.scale-option {
  background: #fff;
  border: 3rpx solid #d0d0d0;
  border-radius: 12rpx;
  padding: 20rpx 24rpx;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.scale-option.active {
  border-color: #5AB89D;
  background-color: #f0faf7;
  box-shadow: 0 4rpx 12rpx rgba(90, 184, 157, 0.2);
}

.scale-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 6rpx;
}

.scale-desc {
  font-size: 24rpx;
  color: #666;
}

.textarea-input {
  width: 100%;
  min-height: 100rpx;
  background: #fff;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 26rpx;
  color: #333;
  box-sizing: border-box;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #5AB89D;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  margin-top: 30rpx;
  border: none;
  box-shadow: 0 4rpx 16rpx rgba(90, 184, 157, 0.3);
  transition: all 0.3s ease;
}

.submit-btn:active {
  background-color: #4aa58b;
  transform: scale(0.98);
}

.submit-btn:disabled {
  background-color: #ccc;
  color: #999;
  box-shadow: none;
}
</style>
